//
// Created by wsl on 2024/3/10.
//

#include "SqString.h"

SqString String_Create(const char *str, size_t size)
{
	if (NULL == str)
		return NULL;

	uin32_t len = strlen(str);

	if (len > size)
		return NULL;

	//实例化对象
	SqString string = DataStructure_AllocT(SqStr);
	if (NULL == string)
	{
		DataStructure_Overflow_Handler();

		return NULL;
	}

	//实例容器
	char *t = DataStructure_Alloc(size);
	if (NULL == t)
	{
		free(string);

		DataStructure_Overflow_Handler();

		return NULL;
	}

	//拷贝数据
	strcpy(t, str);

	//初始化对象
	string->str = t;
	string->length = (int)len;
	string->capacity = size;

	return string;
}

Status String_isEmpty(SqString string)
{
	if (NULL == string)
		return TRUE;

	return string->length <= 0 ? TRUE : FALSE;
}

size_t String_length(SqString string)
{
	if (NULL == string)
		return -1;

	return string->length;
}

Status String_clear(SqString string)
{
	if (NULL == string)
		return FALSE;

	free(string->str);
	string->length = 0;
	string->capacity = 0;

	return TRUE;
}

Status String_append(SqString string1, SqString string2)
{
	if (NULL == string1 || NULL == string2 || !(string1->length && string2->length))
		return FALSE;

	size_t newLength = string1->length + string2->length + 1;

	//超出容量
	if (newLength > string1->capacity)
	{

		//对string1扩容
		char *new = DataStructure_Reallocation(string1->str, newLength);
		if (NULL == new)
		{
			DataStructure_Overflow_Handler();

			return OVERFLOW;
		}

		//更新string1属性
		string1->length = newLength;
		string1->capacity = newLength;
		string1->str = new;
	}

	//拼接
	string1->str = strcat(string1->str, string2->str);

	//更新string1属性
	string1->length = newLength;

	return TRUE;
}

const char* String_value(SqString string)
{
	if (String_isEmpty(string))
		return "";

	return string->str;
}

Status String_destroy(SqString *string)
{
	if (NULL == string || NULL == *string)
		return FALSE;

	String_clear(*string);

	//释放对象本身
	free(*string);

	*string = NULL;

	return TRUE;
}